import axios from 'axios'
import Qs from 'qs'
import store from './store/store'
import codeMethod from './common/js/codeMethod'

//设置全局axios默认值
axios.defaults.timeout = 10000; //10秒的超时验证
axios.defaults.withCredentials = true;//跨域带cookie

function http(type, url, params, contentType) {
  let contentTypeUse = contentType === 'json' ? 'application/json' : 'application/x-www-form-urlencoded';
  let paramsUse = contentType === 'json' ? params : Qs.stringify(params);

  if (type === 'get') {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: url,
        // headers: {},
        params: params
      }).then((res) => {
        resolve(res.data);
        codeMethod(res.data.code, res.data.message);
      }).catch((err) => {
        // Toast('数据获取超时');
        reject(err)
      })
    })
  } else {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: url,
        headers: { 'Content-Type': contentTypeUse },
        data: paramsUse
      }).then((res) => {
        resolve(res.data);
        codeMethod(res.data.code, res.data.message);
      }).catch((err) => {
        // Toast('数据获取超时');
        reject(err)
      })
    })
  }
}

export default http
